package com.meringer.beans.ejb;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.meringer.entities.Car;
import com.meringer.entities.CarModel;
import com.meringer.entities.User;

@Stateless
@LocalBean
public class CarModelEJB {
	@PersistenceContext
	private EntityManager em;
	@EJB
	UserEJB userEJB;
    public CarModelEJB() {
        
    }
    @SuppressWarnings("unchecked")
	public List<CarModel> getCarModels(){
    	//em.createQuery("SELECT name, price FROM T_CAR_MODELS").getResultList()
    	return em.createQuery("SELECT e FROM CarModel e").getResultList();
    }
    public int saveBoughtCar(Integer modelID){
    	CarModel model = em.find(CarModel.class, modelID);
    	User currentUser = userEJB.currentUser();
    	if(model != null){
    		if(currentUser.getBudget() < model.getPrice()){
    			return 1;
    		}
    		for(Car car : currentUser.getCars()){
    			if(model.getModelID() == car.getModel().getModelID()){
    				return 2;
    			}
    		}
    		Car newCar = new Car();
    		newCar.setAcceleration(model.getInitAcceleration());
    		newCar.setHandling(model.getInitHandling());
    		newCar.setTopSpeed(model.getInitTopSpeed());
    		newCar.setModel(model);
    		newCar.setOwner(currentUser);
    		newCar.setPrice(model.getPrice());
    		List<Car> cars = currentUser.getCars();
    		cars.add(newCar);
    		currentUser.setCars(cars);
    		currentUser.setBudget(currentUser.getBudget()-newCar.getPrice());
    		if(currentUser.getMainCar() == null){
    			currentUser.setMainCar(newCar);
    			System.out.println("set");
    		} else {
    			System.out.println(currentUser.getMainCar().equals(""));
    		}
    		em.merge(currentUser);
    	}
    	return 0;
    }

}
